
// Change clientId and apiKey to the associated keys in your API console
var clientId = '';
var apiKey = '';
var profile = '';

// Load the Google Analytics scope
var scopes = 'https://www.googleapis.com/auth/analytics.readonly';

// Array of Chart Objects
var listOfCharts = [];

// Load Visualization API
google.load('visualization', '1', {'packages':['corechart','table']});




// Use a button to handle authentication the first time.

function handleClientLoad() {
    // Load the Visualization API and the piechart package.
    gapi.client.setApiKey(apiKey);
    gapi.auth.init(checkAuth);

    window.setTimeout(checkAuth,1);
}


function checkAuth() {
  setTimeout(function () {
    gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: true}, handleAuthResult);
        }, 1);
}


function handleAuthResult(authResult) {
    var authorizeButton = document.getElementById('authorize-button');
    if (authResult) {
        authorizeButton.style.visibility = 'hidden';

        // Load Google Analytics
        gapi.client.load('analytics', 'v3', function() {

            // Render each chart in the array list
            for(var i = 0; i < listOfCharts.length; i++){
                renderChart(i);
            }
        });



    } else {
        authorizeButton.style.visibility = '';
        authorizeButton.onclick = handleAuthClick;
    }
}

function handleAuthClick(event) {
    gapi.auth.authorize({client_id: clientId, scope: scopes, immediate: false}, handleAuthResult);
    return false;
}

// Here we create a chart object that can take in a list of parameters
// Note: Depending on the 'type' variable, certain parameters are required
// See documentation for all the different parameters a chart object can take with a particular type.
function chart(param){

    // Chart Settings
    this.type = param.type;
    this.divContainer = param.divContainer;
    this.height = param.height;
    this.width = param.width;
    this.title = param.title;

    // Query Settings
    this.metrics = param.metrics;
    this.dimensions = param.dimensions;
	
	if(param.lastNTime) {
		var end = new Date();
		var start = new Date();

		if(param.dimensions == 'ga:date' || param.dimensions == 'ga:day')
			start.setDate(start.getDate() - param.lastNTime);
		else if(param.dimensions == 'ga:hour')
			start.setHours(start.getHours() - param.lastNTime);
		else if(param.dimensions == 'ga:month')
			start.setMonth(start.getMonth() - param.lastNTime);
		else if(param.dimensions == 'ga:year')
			start.setYear(start.getFullYear() - param.lastNTime);
		else if(param.dimensions == 'ga:week')
			start.setDate(start.getDate() - (param.lastNTime * 7));
		else
			error('Invalid lastNTime parameter');

		this.enddate = parseDate(end);
		this.startdate = parseDate(start);
		document.write(this.enddate + '<br>' + this.startdate);
	}
	else {
		this.startdate = param.startdate;
		this.enddate = param.enddate;
	}

    //Optional Params

    this.xAxisLabel = param.xAxisLabel;
    this.yAxisLabel = param.yAxisLabel;
    this.xMax = param.xMax;
    this.yMax = param.yMax;

    // Adds the chart object that we just created with the parameters to
    // the array of charts to render
    listOfCharts.push(this);
}

function parseDate(date) {
	var year = date.getFullYear();
	var month = date.getMonth() + 1;
	var day = date.getDate();
	
	if(month < 10)
		month = '0' + month;
	if(day < 10)
		day = '0' + day;

	return (year + '-' + month + '-' + day);
}

function renderChart(chartNumber){

        var chart = listOfCharts[chartNumber];

        var request = gapi.client.analytics.data.ga.get({
            'ids': profile,
            'start-date': chart.startdate,
            'end-date': chart.enddate,
            'metrics': chart.metrics,
            'dimensions': chart.dimensions

        });

        request.execute(function(resp) {
            drawChart(resp, listOfCharts[chartNumber]);
        });
}



// Creates a new chart using a JSON response and a chart type.
// Chart Types:
// Line Graph = 1 , Bar Graph = 2, Pie Graph = 3
function drawChart(resp, chart){

    switch (chart.type)
    {
        case 'line':
            lineGraph(resp, chart);
            break;
        case 'bar':
            //barGraph(resp);
            break;
        case 'pie':
            //pieGraph(resp);
            break;
        default:
            table(resp, chart);
    }
}

function requestAccountInfo() {
    requestAccountId(function (accountId) {
        window.accountId = accountId;
        requestWebPropertyId(function (webPropertyId) {
            window.webPropertyId = webPropertyId;
            requestProfileId(function (profileId) {
                window.profileId = profileId;
                alert(window.profileId);
            });
        });
    });
}

function requestAccountId(callback) {
    var requestAccountId = gapi.client.analytics.management.accounts.list();
    requestAccountId.execute(function (resp) {
        var accountId = resp.items[0].id;
        callback(accountId);
    });
}

function requestWebPropertyId(callback) {
    var requestWebPropertyId = gapi.client.analytics.management.webproperties.list({'accountId':accountId});
    requestWebPropertyId.execute(function (resp) {
        var webPropertyId = resp.items[0].id;
        callback(webPropertyId);
    });
}

function requestProfileId(callback) {
    var requestProfileId = gapi.client.analytics.management.profiles.list({'accountId':accountId, 'webPropertyId':webPropertyId});
    requestProfileId.execute(function (resp) {
        var profileId = resp.items[0].id;
        callback(profileId);
    });
}

function lineGraph(resp, chart){

    // Sets the settings for the div tag to display chart
    var divID = chart.divContainer;
    var width = chart.width;
    var height = chart.height;

    if(!height){
        error('No height was set');
    }

    // Chart details
    var title = chart.title;


    // Create and populate the data table.
    var data = new google.visualization.DataTable();

    var numOfMetrics = resp.query.metrics.length;
    var numResults = resp.totalResults;

    data.addColumn('string', 'x');
    for(var i = 0; i < numOfMetrics; i++){
        data.addColumn('number', resp.query.metrics[i]);
    }

    for(var i = 0; i < numResults; i++){

        var uDateString = resp.rows[i][0];
        var arrayMetrics = [uDateString];

        for(var j = 1; j <= numOfMetrics; j++ ){
            arrayMetrics.push(parseInt(resp.rows[i][j]));
        }

        data.addRow(arrayMetrics);

    }


    // Create and draw the visualization.
    new google.visualization.LineChart(document.getElementById(divID)).
        draw(data, {curveType: "function",
           title: title, titleTextStyle: {color: 'black', fontName: 'arial', fontSize: 24},
            height: height, width: width

        }
    );

}


function table(resp, chart) {

    var data = new google.visualization.DataTable();
    var numOfHeaders = resp.columnHeaders.length;

    for(var i = 0; i < numOfHeaders; i++){
        data.addColumn('string', resp.columnHeaders[i].name);
    }

    var numResults = resp.totalResults;

    data.addRows(numResults);

    var numOfHeaders = resp.columnHeaders.length;

    for(var i = 0; i < numOfHeaders; i++){
        for(var j = 0; j < numResults; j++){
            data.setCell(j, i, resp.rows[j][i]);
        }
    }

    // Create and draw the visualization.
    visualization = new google.visualization.Table(document.getElementById(chart.divContainer));
    visualization.draw(data, null);


}


// Lets the user set the apiKey, clientID and profile id
function configAccount(settings){
    this.apiKey = settings.apiKey;
    this.clientId = settings.clientId;
    this.profile = settings.profileId;
    this.buttonId = settings.buttonId;
}

function error(message){
    alert(message);
}




















